<!--hmc 创建用户旅程第一步：设置规则-->
<template>
  <div class="page-container page-container-create">
    <!--面包屑-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>会员中心</el-breadcrumb-item>
        <el-breadcrumb-item>折扣卡管理</el-breadcrumb-item>
        <el-breadcrumb-item>扣卡列表</el-breadcrumb-item>
        <el-breadcrumb-item>创建折扣卡</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div >
      <p class="title t_l mb50 mt40">{{id == 0 ? '创建折扣卡规则' : '编辑折扣卡规则'}}</p>
      <el-form :model="ruleForm" size="mini" ref="ruleForm" :rules="ruleFormRules" class="mb60">

        <el-form-item label="折扣卡名称：" prop="discountThemeName" class="mb30"  label-width="118px">
          <el-input
            clearable
            v-model="ruleForm.discountThemeName"
            placeholder="输入折扣卡名称"
            size="mini"
            maxlength="64"
            class="w410"
          ></el-input>
          <el-tooltip class="item turnInlineBlock" effect="dark" content="最多输入64个字符" placement="right" popper-class="atooltip">
            <span class="tips">!</span>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="折扣限制：" prop="discountValue" class="mb30" label-width="118px"> 
          <el-input
            clearable
            v-model="ruleForm.discountValue"
            placeholder="请输入折扣数值，如8、7.5"
            size="mini"
            minlength="3"
            maxlength="30"
            class="w410"
          ></el-input>
          <span>折</span>
        </el-form-item>

        <el-form-item label="有效期：" prop="rangeTime" class="mb30" label-width="118px">
            <el-date-picker
              v-model="ruleForm.rangeTime"
              range-separator="至"
              type="datetimerange"
              value-format="timestamp"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="timeCheck"
              style="width:410px"
            ></el-date-picker>
        </el-form-item>


        <el-form-item label="使用渠道：" class="mb30" :required="true" :show-message="false" v-if="deptType == 0" label-width="118px">
            <el-tree
              :data="channelList"
              :props="channlProps"
              show-checkbox
              :default-expand-all="true"
              node-key="id"
              ref="channelTree"
              style="width:600px;"
            ></el-tree>
        </el-form-item>

        <el-form-item label="备注：" prop="remark"  label-width="118px">
            <el-input
              type="textarea"
              v-model="ruleForm.remark"
              @input="changeInput($event)"
              placeholder="请填写备注"
              class="remarks w430"
              maxlength="1000"
              :rows="4"
              clearable
            ></el-input>
          <el-tooltip class="item turnInlineBlock"  effect="dark" content="最多输入1000个字符" placement="right" popper-class="atooltip">
            <span class="tips" >!</span>
          </el-tooltip>
        </el-form-item>

      </el-form>
      <div class=" t_c">
        <el-button class="cancelButton mr60" @click="back()">取消</el-button>
        <el-button class="searchButton" @click="submit()">确定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import marketRequest from "@/discountCard/request/cardRequest";
  export default {
    name: "discountCardCreate",
    components: {},
    computed: {
      mainTabs: {
        get() {
          return this.$store.state.tab.mainTabs;
        },
        set(val) {
          this.$store.commit("updateMainTabs", val);
        }
      },
      mainTabsActiveName: {
        get() {
          return this.$store.state.tab.mainTabsActiveName;
        },
        set(val) {
          this.$store.commit("updateMainTabsActiveName", val);
        }
      }
    },
    data() {

      var checkDiscountValue = (rule, value, callback) => {
        if(!value){
          return callback(new Error("请设置折扣限制"));
        }
        var reg = /^(?!0(\.0{1,1})?$)(\d(\.\d{1,1})?|10)$/;
        if (!reg.test(value)) {
          return callback(new Error("请输入正确的折扣数值"));
        }
        return callback();
      };

      return {
        id: this.$route.params.id,
        deptType: localStorage.getItem("deptType"), //当前登录用户所属组织类型
        //form
        ruleForm: {
          discountThemeName: null,  //折扣卡主题名称
          discountValue: null,  //折扣卡主题名称
          rangeTime: null,  //折扣卡主题名称
          remark: null,  //折扣卡主题名称
        },
        //渠道Tree List
        channelList: [],
        channlProps: {
          children: "children",
          label: "childName"
        },
        //form规则
        ruleFormRules: {
          discountThemeName: [
            { required: true, message: "请设置折扣卡名称", trigger: "blur" }
          ],
          rangeTime: [
            { required: true, message: "请设置有效期", trigger: "blur" }
          ],
          discountValue: [
            { required: true, validator: checkDiscountValue, trigger: "blur" },
          ],
        },
        // 时间校验
        timeCheck: {
          disabledDate: time => {
            if (this.time) {
              return (
                time.getTime() < Date.now() - 8.64e7 ||
                time.getTime() > new Date(this.time).getTime()
              );
            } else {
              return time.getTime() < Date.now() - 8.64e7;
            }
          }
        },
      };
    },

    methods: {
      // tabs, 删除tab
      removeTabHandle(tabName) {
        this.mainTabs = this.mainTabs.filter(item => item.name !== tabName);
        if (this.mainTabs.length >= 1) {
          // 当前选中tab被删除
          if (tabName === this.mainTabsActiveName) {
            let tab = this.mainTabs[this.mainTabs.length - 1];
            this.$router.push(
              { path: tab.path,params: tab.params, query: tab.query},
              () => {
                this.mainTabsActiveName = this.$route.name;
              }
            );
          }
        } else {
          this.$router.push("/");
        }
      },

      //输入框无法输入问题
      changeInput(val) {
        this.$forceUpdate();
      },

      //提交更新
      submit(){
        let this_ = this;
        this.$refs["ruleForm"].validate(valid => {
          if (valid) {
            //当前登录用户身份为母平台校验所属渠道
            // if (this.deptType == 0) {
            //   if (this.$refs.channelTree.getCheckedKeys().length <= 0) {
            //     this.$message({ message: "请选择使用渠道" });
            //     loading.close();
            //     return false;
            //   } else {
            //     this.ruleForm.channelCodes = this.$refs.channelTree
            //       .getCheckedKeys()
            //       .join(",");
            //   }
            // }
            this.ruleForm.startTime = this.ruleForm.rangeTime[0];
            this.ruleForm.endTime = this.ruleForm.rangeTime[1];

            let callback = function(res) {
              if (res.code == "0000") {
                this_.id = res.data;
                this_.removeTabHandle("创建折扣卡");
                this_.$router.push(`/Pages/DiscountCard/DiscountCard`);
              }
            };
            if(this.id != 0){
              this.ruleForm.id = this.id;
            }else{
              this.ruleForm.id = null;
            }
            marketRequest.createDiscountTheme(this.ruleForm, callback)
          }
        });
      },

      // 点击取消返回用户旅程列表
      back() {
        this.removeTabHandle("创建折扣卡");
        //this.$router.push(`/Pages/DiscountCard/DiscountCard`);
      },

      //获取旅程基本信息
      getDiscountThemeInfo(){
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
            this_.ruleForm.discountThemeName =  res.data.discountThemeName;
            this_.ruleForm.discountValue =  res.data.discountValue;
            this_.ruleForm.remark =  res.data.remark;
            if (this_.deptType == 0) {
              this_.$refs.channelTree.setCheckedKeys(
                res.data.channelCodes.split(",").map(item => parseInt(item))
              );
            }

            this_.$set(this_.ruleForm, "rangeTime", [
              new Date(res.data["startTime"]).getTime(),
              new Date(res.data["endTime"]).getTime()
            ]);
          }
        };
        if(this.id){
          this.ruleForm.id = this.id;
        }
        marketRequest.queryDiscountThemeInfo({id: this.id}, callback)
      },

      //获取子平台列表
      getChildList() {
        let this_ = this;
        let channel = { childName: "卡奥斯运营中心", id: "179" };
        this.utils.request.queryChildList({}, res => {
          if (res.code == "0000" && res.data && res.data.length > 0) {
            channel.children = res.data;
            this_.channelList.push(channel);
            if (typeof this_.id == "undefined" || this_.id == 0) {
              this_.$nextTick(() => {
                this_.$refs.channelTree.setChecked("179", true, false);
                res.data.forEach(item => {
                  this_.$refs.channelTree.setChecked(item.id, true, false);
                });
              });
            }
          }
        });
      },

    },

    created(){
      if (localStorage.getItem("deptType") && localStorage.getItem("deptType") == 0) {
        this.getChildList();
      }
    },

    mounted() {
      if (typeof this.$route.params.id != "undefined") {
        this.id = this.$route.params.id;
         if(this.id != 0){
           this.getDiscountThemeInfo();
         }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .desc{
    color: #ffb100;
    font-size: 10px;
    margin-top: 10px;
    margin-left: 108px;
  }

  .title {
    font-size: 16px;
    text-align: left;
  }
  .part {
    padding: 0 40px;
  }
  /deep/ .el-radio {
    margin-right: 80px;
    position: relative;
    .icon {
      background: #ffbf5e;
      color: #fff;
      width: 10px;
      height: 10px;
      line-height: 10px;
      padding: 2px;
      border-radius: 50%;
      font-size: 10px;
      text-align: center;
      display: block;
      position: absolute;
      right: -20px;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .mb50{
    margin-bottom: 50px;
  }
  .mt40{
    margin-top: 40px;
  }
  /deep/ .w410{
    width: 410px;
    .el-input__inner{
      width: 410px;
    }
  }
  .mb120{
    margin-bottom: 120px;
  }
  /deep/ .el-tooltip__popper .is-dark {
    font-size: 20px !important;
  }
  /* 错误提示样式重置 */
  // /deep/ .el-form-item__error {
  //   color: #F56C6C;
  //   font-size: 12px;
  //   line-height: 1;
  //   padding-top: 4px;
  //   position: absolute;
  //   top: 100%;
  //   left: 108px;
  // }
  .tips{
    width: 17px ;
    height: 17px;
    border-radius: 8.5px;
    background-color: #FDCB0E;
    color: #fff;
    text-align:center;
    line-height: 17px;
  }
  .w430{
    width: 430px;
  }
</style>

